<template>
  <div class="app-container">
    <div class="filter-container">
      <TreeSelect v-model="listQuery.pid" :nodes="pNodes" placeholder="父节点"></TreeSelect>
      <el-input v-model="listQuery.name" placeholder="名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.url" placeholder="路径" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.type" placeholder="类型" clearable style="width: 110px" class="filter-item">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-view" @click="handleTree">
        权限总览
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="父节点" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pname == null ? '/' : row.pname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="页面缓存" width="80px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cache == 0 ? '不缓存' : '缓存' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type == 0 ? '菜单' : '资源' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图标" width="160px" align="center">
        <template slot-scope="{row}">
          <i :class="row.icon" />
        </template>
      </el-table-column>
      <el-table-column label="路径" width="160px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.description" />
        </el-form-item>
        <el-form-item label="父节点" prop="pid">
          <TreeSelect v-model="temp.pid" :nodes="pNodes"></TreeSelect>
        </el-form-item>
        <el-form-item label="页面缓存">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="temp.cache">
          </el-switch>
          <span style="position: absolute;left: 80px;font-size: small;font-weight: 300">{{temp.cache == 0? '不缓存':'缓存'}}</span>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="temp.orderNum" />
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="temp.icon" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择" @change="changeType">
            <el-option v-for="item in typeNewOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="路径">
          <el-input v-model="temp.url" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="权限总览" :visible.sync="permsTreeStatus">
      <el-tree
        ref="tree"
        :data="treeData"
        node-key="id"
        class="permission-tree"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>
                <i :class="data.icon"></i>{{ data.description }}&nbsp;
                <span :style="'font-size:8px;'+ (data.type == 0 ? 'color:#1890ff;' : 'color:#42b983;')">[{{ data.type == 0 ? '菜单' : '资源' }}] {{data.url}}</span>
            </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="closeTree()">
          关闭
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { permissionList, permissionTree, permissionCreate, permissionUpdate,permissionDelete } from '@/api/sys'
  import waves from '@/directive/waves' // waves directive
  import Pagination from '@/components/Pagination'
  import TreeSelect from '@/components/TreeSelect'

  export default {
    name: 'sysPermission',
    components: { Pagination, TreeSelect},
    directives: { waves },
    filters: {
      statusFilter(status) {
        const statusMap = {
          0: 'danger',
          1: 'success'
        }
        return statusMap[status]
      },
      sexFilter(status) {
        const statusMap = {
          1: 'error',
          2: 'danger'
        }
        return statusMap[status]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 15,
          name: '',
          url: '',
          type: '',
          sort: '+id'
        },
        typeOptions: [{ value:'', label:'类型-全部'}, { value:'0', label:'菜单'}, { value:'1', label:'资源'}],
        typeNewOptions: [{ value:'0', label:'菜单'}, { value:'1', label:'资源'}],
        temp: {
          id: undefined,
          name: '',
          description: '',
          url: '',
          pid: '',
          type: '',
          orderNum: '',
          icon: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          name: [{ required: true, message: '请填写名称', trigger: 'blur' }],
          pid: [{ required: true, message: '请选择父节点', trigger: 'blur' }]
        },
        permsTreeStatus: false,
        treeData: [],
        treeHeight: 200,
        pNodes: [],
        pSize: 0,
        label: ''
      }
    },
    created() {
      this.getList()

      this.pNodes.length = 0
      permissionTree({roleId:[]}).then(response => {
        var root = {id: '0', name: '/', children: []}
        this.pNodes.push(root)
        this.parseTree(root, response.data.tree);
      })
    },
    methods: {
      getList() {
        this.listLoading = true
        permissionList(this.listQuery).then(response => {
          this.list = response.data.content
          this.total = parseInt(response.data.totalElements)

          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          name: '',
          description: '',
          url: '',
          pid: '',
          type: '0',
          orderNum: '0',
          icon: 'el-icon-price-tag'
        }
      },
      handleCreate() {
        this.resetTemp()
        this.pNodes.length = 0
        permissionTree({roleId:[]}).then(response => {
          var root = {id: '0', name: '/', children: []}
          this.pNodes.push(root)
          this.parseTree(root, response.data.tree);

          this.dialogStatus = 'create'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      },
      parseTree(root, tree){
        tree.forEach(item => {
          if(item.type == 0){
            var node = {};
            node.id = item.id
            node.name = item.description
            node.icon = item.icon
            node.children = []
            root.children.push(node)
            this.pSize ++
            if (item.children) {
              this.parseTree(node, item.children)
            }
          }
        })
      },
      checkGroupNode: function (a, b) {
        if (b.checkedKeys.length > 0) {
          this.$refs.tree.setCheckedKeys([a.id]);
          this.temp.pid = a.id
          this.label = a.name
        }
      },
      handleTree() {
        permissionTree({roleId:[]}).then(response => {
          this.treeData = response.data.tree;
          this.$nextTick(() => {
            for (var i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
              if(this.$refs.tree.store._getAllNodes()[i].level < 2){
                this.$refs.tree.store._getAllNodes()[i].expanded = true
              }
            }
          })
          this.permsTreeStatus = true
        })
      },
      closeTree(){
        this.permsTreeStatus = false
        this.$nextTick(() => {
          this.treeData = []
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            permissionCreate(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        this.pNodes.length = 0

        permissionTree({roleId:[]}).then(response => {
          var root = {id: '0', name: '/', children: []}
          this.pNodes.push(root)
          this.parseTree(root, response.data.tree);

          this.temp = Object.assign({}, row) // copy obj
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            permissionUpdate(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      handleDelete(row, index) {
        const tempData = {};
        tempData.id = row.id;
        const that = this;
        this.$confirm('确认删除？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          cancelButtonClass: 'btn-custom-cancel',
          type: 'warning'
        }).then(function(){
          permissionDelete(tempData).then(() => {
            that.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
            that.getList()
          })
        }).catch(function(){
          // console.log("取消成功！");
        })
      },
      changeType(value){
        if(this.temp.icon == 'el-icon-price-tag' || this.temp.icon == 'el-icon-thumb'){
          if(value == 0){
            this.temp.icon = 'el-icon-price-tag'
          }else{
            this.temp.icon = 'el-icon-thumb'
          }
        }
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>

<style lang="scss" scoped>

  .user-avatar {
    cursor: pointer;
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }

</style>
